package gong.gm.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gong.gm.auth.entity.CustomMd5PasswordEncoder;
import gong.gm.auth.entity.CustomUserDetail;
import gong.gm.mapper.SysUserMapper;
import gong.gm.pojo.dto.SysUser;
import gong.gm.pojo.vo.LoginVo;
import gong.gm.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;
import java.util.Random;

/**
 * @author voloiono
 * @date 2024/6/25 11:51
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public SysUser queryUserByName(String name) {
        return sysUserMapper.GetUserByUserName("name");
    }

    @Override
    public String login(LoginVo loginVo) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginVo.getUsername(), loginVo.getPassword());

        Authentication authenticated = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticated)) {
            throw new RuntimeException("username or password error");
        }

        CustomUserDetail userDetail = (CustomUserDetail) authenticated.getPrincipal();
        SysUser sysUser = userDetail.getSysUser();

        DateTime now = DateTime.now();
        DateTime newTime = now.offset(DateField.DAY_OF_MONTH, 1);

        Random random = new Random();
        int randomInt = random.nextInt(100000000);
        String key = String.format("%09d", randomInt);

        HashMap<String, Object> jwtMap = new HashMap<>();
        jwtMap.put(JWTPayload.ISSUED_AT, now);
        jwtMap.put(JWTPayload.EXPIRES_AT, newTime);
        jwtMap.put(JWTPayload.NOT_BEFORE, now);
        jwtMap.put("username", sysUser.getUsername());
        jwtMap.put("password", sysUser.getPassword());
        String token = JWTUtil.createToken(jwtMap, key.getBytes());

        sysUserMapper.update(new SysUser(),new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getKey,key)
                .set(SysUser::getToken,token)
                .set(SysUser::getStatus,1)
                .eq(SysUser::getUsername,sysUser.getUsername()));

        return token;
    }
}
